import UIKit
import Flutter
import AdSupport
import AppTrackingTransparency

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      let controller:FlutterViewController = window.rootViewController as! FlutterViewController
      let appGetChannel = FlutterMethodChannel(name: "app.get.channel", binaryMessenger: controller as! FlutterBinaryMessenger)
      appGetChannel.setMethodCallHandler { (call, result) in
          if "getDeviceId" == call.method {
              let manager = ASIdentifierManager.shared()
                   if #available(iOS 14.0, *) {
                       if (ATTrackingManager.trackingAuthorizationStatus == ATTrackingManager.AuthorizationStatus.authorized) {
                           result(manager.advertisingIdentifier.uuidString)
                       } else {
                           ATTrackingManager.requestTrackingAuthorization { status in
                               if (status == ATTrackingManager.AuthorizationStatus.authorized) {
                                   result(manager.advertisingIdentifier.uuidString)
                               } else {
                                   result("")
                               }
                           }
                       }
                   } else {
                       var idfaString: String!
                       if manager.isAdvertisingTrackingEnabled {
                           idfaString = manager.advertisingIdentifier.uuidString
                       } else {
                           idfaString = ""
                       }
                       result(idfaString)
                   }
          } else {
              result(FlutterMethodNotImplemented)
          }
      }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    override func applicationDidBecomeActive(_ application: UIApplication) {
                if #available(iOS 14.0, *) {
                    if (ATTrackingManager.trackingAuthorizationStatus != ATTrackingManager.AuthorizationStatus.authorized) {
                        ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                            
                        })
                    }
                    
                }
            }

}
